<template>
    <view class="addWorker">
        <!-- 基础表单 -->
        <view class="base">
            <view class="row flex_b">
                <view class="label">手机号</view>
                <view class="value">
                    <up-input inputAlign="right" type="number" placeholder="输入联系方式" border="none"
                        v-model="form.customerMobile"></up-input>
                </view>
            </view>
            <view class="row flex_b">
                <view class="label">计费模式</view>
                <view class="value radio">
                    <view class="item flex_r" @click="form.feeType = '1'">
                        <image v-if="form.feeType == '1'" style="width: 28rpx;height: 28rpx;margin-right: 16rpx;"
                            src="@/static/images/customerPage/icon_select.png" />
                        <image v-else style="width: 28rpx;height: 28rpx;margin-right: 16rpx;"
                            src="@/static/images/customerPage/icon_unselect.png" />
                        <text>一口价</text>
                    </view>
                    <view class="item flex_r" @click="form.feeType = '2'">
                        <image v-if="form.feeType == '2'" style="width: 28rpx;height: 28rpx;margin-right: 16rpx;"
                            src="@/static/images/customerPage/icon_select.png" />
                        <image v-else style="width: 28rpx;height: 28rpx;margin-right: 16rpx;"
                            src="@/static/images/customerPage/icon_unselect.png" />
                        <text>计件</text>
                    </view>
                </view>
            </view>
            <view class="row flex_b">
                <view class="label">{{ form.feeType == '1' ? '需要人数' : '件数' }}</view>
                <view class="value">
                    <up-number-box integer v-model="form.peopleNum"></up-number-box>
                </view>
            </view>
            <view class="row flex_b" @click="toPrice">
                <view class="label">市场行情参考</view>
                <view class="value">
                    <up-icon name="arrow-right" color="#222222" size="16"></up-icon>
                </view>
            </view>
            <view class="row flex_b">
                <view class="label">我愿出价<text class="label_tips"> (参考价)</text></view>
                <view class="value">
                    <up-input inputAlign="right" type="digit" placeholder="输入金额" border="none" v-model="form.unitPrice"
                        @blur="onBlur">
                        <template #suffix>
                            <view class="suffix">{{ form.feeType == '1' ? '元/人' : '元/件' }}</view>
                        </template>
                    </up-input>
                </view>
            </view>
            <view class="row flex_b" style="border: none !important;">
                <view class="label">我愿出价<text class="label_tips"> (总价)</text></view>
                <view class="value">
                    <up-input inputAlign="right" disabled type="digit" placeholder="输入金额" border="none"
                        v-model="form.money">
                        <template #suffix>
                            <view class="suffix">元</view>
                        </template>
                    </up-input>
                </view>
            </view>
            <!-- <view class="base_tips">不足半小时，按照半小时计费，超时每半小时计费一次</view> -->
        </view>
        <!-- 内容介绍 -->
        <view class="supplement">
            <view class="supplement_title flex_l">内容介绍</view>
            <up-textarea border="none" v-model="form.introduction" placeholder="请如实填写详细的内容介绍"></up-textarea>
        </view>
        <!-- 补充需求 -->
        <view class="supplement">
            <view class="supplement_title flex_l">对工人有什么要求</view>
            <up-textarea border="none" v-model="form.orderDsg" placeholder="例如需要带绳子、推拉车等"></up-textarea>
            <view class="uplaod">
                <myUploadImg @uploadImgSuccess="uploadImgSuccess" @deleteImg="deleteImg"></myUploadImg>
            </view>
        </view>
        <!-- 计费金额 -->
        <view class="price">
            <view class="price_title flex_b">
                <view>计费金额</view>
                <view style="color:#FE6E04;" @click="selectCoupon">{{ form.couponMoney > 0 ? `优惠券金额:
                    ${form.couponMoney}` :
                    '使用优惠券' }}
                </view>
            </view>
            <view class="money" v-if="form.pay > 0">¥{{ (form.pay).toFixed(2) }}</view>
            <view class="money money_placeholder" v-else>¥0.00</view>
            <view class="price_tips">
                <view class="item">
                    <image src="@/static/images/customerPage/icon_rule.png" />
                    <text>计费规则</text>
                </view>
                <view class="line"></view>
                <view class="item">
                    <image src="@/static/images/customerPage/icon_price.png" />
                    <text>预估明细</text>
                </view>
            </view>
        </view>
        <!-- 底部按钮 -->
        <view class="bottom_btn">
            <view class="btn flex_c" @click="toDetial">确认用工</view>
        </view>
    </view>
</template>

<script lang="ts" setup>
import { ref, watchEffect, getCurrentInstance } from 'vue';
import myUploadImg from '@/components/my-uploadImg/my-uploadImg.vue';
import { onLoad, onUnload } from '@dcloudio/uni-app';
import { createOrder } from "@/api/customerPage/order"
import type { OrderParams } from "@/types/order"
import { useMemberStore } from '@/stores'

onLoad(() => {
    const instance: any = getCurrentInstance()?.proxy
    const eventChannel = instance.getOpenerEventChannel()
    eventChannel.on('selectWorkerForm', function (data: any) {
        for (let key in data) {
            form.value[key] = data[key]
        }
    })
    const { memberInfo } = useMemberStore()
    if (memberInfo?.mobile) {
        form.value.customerMobile = memberInfo?.mobile
    }
})

const form = ref<OrderParams>({
    customerMobile: "", // 手机号
    workType: "", // 工种
    workDate: "", // 开工时间
    workPlace: "", // 开工地址
    address: "", // 详细地址
    status: 0, // 状态
    feeType: "1",  // 1 一口价 2工时计价
    peopleNum: 1,  // 需要人数/件数
    workHour: 1, // 工时
    unitPrice: 0, // 单价 
    introduction: "",
    orderDsg: "", // 订单备注
    money: 0, // 金额
    pay: 0, // 支付金额
    couponId: "", // 优惠券id
    couponMoney: 0,
    customerImages: "", // 图片
    lat: 0, // 经度
    lng: 0, // 纬度
    userIp: "127.0.0.1"
})

watchEffect(() => {
    // 计算规则 单价以人数
    const money = (form.value.unitPrice as number) * form.value.peopleNum
    form.value.money = Number(money.toFixed(2))
    // 如果使用了优惠券 但是修改价格为低于优惠券时候，则不减
    if (form.value.couponMoney > 0 && form.value.money < form.value.couponMoney) {
        uni.showToast({
            title: '优惠券金额大于订单金额，请重新选择优惠券',
            icon: 'none'
        })
        form.value.couponMoney = 0
        form.value.couponId = ""
    }
    form.value.pay = money - form.value.couponMoney
})
// 价钱不能低于0
const onBlur = () => {
    form.value.unitPrice = Math.max(0, form.value.unitPrice as number)
}
// 上传图片
const customerImagesList = ref<string[]>([])
const uploadImgSuccess = (url: string) => {
    customerImagesList.value.push(url)
}
const deleteImg = (index: number) => {
    customerImagesList.value.splice(index, 1)
}
// 选择优惠券
const selectCoupon = () => {
    if (form.value.money == 0) {
        uni.showToast({
            title: '请输入价格',
            icon: 'none'
        })
        return
    }
    uni.$off('selectCoupon'); //关闭监听
    uni.$on('selectCoupon', (data: any) => {
        setCoupon(data)
    })
    uni.navigateTo({
        url: `/pages/other/coupon/coupon?money=${form.value.money}`
    })
}
const setCoupon = (data: any) => {
    if (!data) return
    form.value.couponMoney = data.discountPrice
    form.value.couponId = data.id
    // 支付价 总价减去优惠券
    form.value.pay = (form.value.money as number) - data.discountPrice
    uni.$off('selectCoupon'); //关闭监听
}
// 确认
const toDetial = (() => {
    // 价格校验
    if (form.value.money == 0) {
        uni.showToast({
            title: '请输入价格',
            icon: 'none'
        })
        return
    }
    // 图片校验
    if (customerImagesList.value.length == 0) {
        uni.showToast({
            title: '至少上传一张图片',
            icon: 'none'
        })
        return
    }
    form.value.customerImages = customerImagesList.value.join(",")
    uni.showLoading({
        title: '提交中...'
    })
    const par = JSON.parse(JSON.stringify(form.value))
    createOrder(par).then((res: any) => {
        if (res.code == 0) {
            uni.showToast({
                title: "提交成功!",
                icon: 'none'
            })
        }
        uni.hideLoading()
        setTimeout(() => {
            uni.navigateTo({
                url: `/pages/customerPage/workerDetial/workerDetial?id=${res.data}`
            })
        }, 1000)
    })
})
// 查看市场行情
const toPrice = () => {
    uni.navigateTo({
        url: `/pages/public/marketCondition/marketCondition`
    })
}
onUnload(() => {
    uni.$off('selectCoupon')
})
</script>

<style lang="scss" scoped>
@import "./addWorker.scss";
</style>